<template>
  <div class="admin-container">
    <h1 class="text-2xl font-bold mb-6">管理员面板</h1>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
      <!-- 用户统计卡片 -->
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center">
          <div class="rounded-full bg-blue-100 p-3 mr-4">
            <font-awesome-icon icon="users" class="text-blue-500 text-xl" />
          </div>
          <div>
            <p class="text-gray-500">总用户数</p>
            <p class="text-2xl font-bold">{{ userStats.total }}</p>
          </div>
        </div>
      </div>

      <!-- 在线用户卡片 -->
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center">
          <div class="rounded-full bg-green-100 p-3 mr-4">
            <font-awesome-icon icon="user-check" class="text-green-500 text-xl" />
          </div>
          <div>
            <p class="text-gray-500">在线用户</p>
            <p class="text-2xl font-bold">{{ userStats.online }}</p>
          </div>
        </div>
      </div>

      <!-- 管理员卡片 -->
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex items-center">
          <div class="rounded-full bg-purple-100 p-3 mr-4">
            <font-awesome-icon icon="user-shield" class="text-purple-500 text-xl" />
          </div>
          <div>
            <p class="text-gray-500">管理员数</p>
            <p class="text-2xl font-bold">{{ userStats.admins }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户管理表格 -->
    <div class="bg-white rounded-lg shadow">
      <div class="px-6 py-4 border-b border-gray-200">
        <h2 class="text-lg font-semibold">用户管理</h2>
      </div>

      <div class="p-6">
        <div class="flex justify-between items-center mb-4">
          <div class="flex space-x-3">
            <!-- 刷新按钮 -->
            <button
                class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded flex items-center"
                @click="refreshData"
            >
              <font-awesome-icon class="mr-2" icon="sync"/>
              刷新
            </button>

            <!-- 已删除：查看报表按钮 -->
          </div>

          <!-- 搜索框 -->
          <div>
            <input
                v-model="searchKeyword"
                class="border border-gray-300 rounded px-4 py-2"
                placeholder="搜索用户名..."
                type="text"
                @input="handleSearch"
            />
          </div>
        </div>

        <!-- 用户表格 -->
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户名</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">角色</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">注册时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="user in users" :key="user.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ user.id }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ user.username }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                  <span
                      :class="{
                      'bg-blue-100 text-blue-800': user.role === 'USER',
                      'bg-purple-100 text-purple-800': user.role === 'ADMIN'
                    }"
                      class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                  >
                    {{ user.role === 'ADMIN' ? '管理员' : '普通用户' }}
                  </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ user.email || '未设置' }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ user.createdAt ? formatDate(user.createdAt) : '未知' }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <button
                    v-if="user.role !== 'ADMIN'"
                    @click="promoteUser(user.id)"
                    class="text-green-600 hover:text-green-900 mr-3"
                >
                  设为管理员
                </button>
                <button
                    v-if="user.role === 'ADMIN' && user.username !== currentUser.username"
                    @click="demoteUser(user.id)"
                    class="text-yellow-600 hover:text-yellow-900 mr-3"
                >
                  取消管理员
                </button>
                <button
                    v-if="user.username !== currentUser.username"
                    @click="deleteUser(user.id)"
                    class="text-red-600 hover:text-red-900"
                >
                  删除
                </button>
                <span v-else class="text-gray-400">-</span>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="flex items-center justify-between mt-4">
          <div class="text-sm text-gray-500">
            显示第 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, total) }} 条记录，
            总共 {{ total }} 条记录
          </div>
          <div class="flex space-x-2">
            <button
                :class="currentPage === 1 ? 'bg-gray-100 text-gray-400' : 'bg-white hover:bg-gray-50'"
                :disabled="currentPage === 1"
                class="px-3 py-1 rounded border"
                @click="prevPage"
            >
              上一页
            </button>
            <button
                :class="currentPage * pageSize >= total ? 'bg-gray-100 text-gray-400' : 'bg-white hover:bg-gray-50'"
                :disabled="currentPage * pageSize >= total"
                class="px-3 py-1 rounded border"
                @click="nextPage"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import {
  getUserPageApi,
  getUserListApi,
  updateUserApi,
  deleteUserApi,
  getOnlineUserCountApi
} from '@/api/user'

export default {
  name: 'Admin',
  data() {
    return {
      userStats: {total: 0, online: 0, admins: 0},
      users: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      searchKeyword: '',
      currentUser: {},
      searchTimeout: null
    }
  },
  mounted() {
    this.loadUserStats()
    this.loadUsers()
    this.loadCurrentUser()
  },
  methods: {
    // 加载用户统计
    async loadUserStats() {
      try {
        const pageRes = await getUserPageApi(1, 1)
        this.userStats.total = pageRes.data.total
        const listRes = await getUserListApi()
        this.userStats.admins = listRes.data.filter(u => u.role === 'ADMIN').length
        // 获取在线用户数
        const onlineRes = await getOnlineUserCountApi()
        this.userStats.online = onlineRes.data || 0
      } catch (err) {
        console.error('加载统计失败:', err)
      }
    },

    // 加载用户列表
    async loadUsers() {
      try {
        let response
        if (this.searchKeyword.trim()) {
          response = await getUserListApi()
          const filtered = response.data.filter(u =>
              u.username?.toLowerCase().includes(this.searchKeyword.toLowerCase())
          )
          this.users = filtered.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
          this.total = filtered.length
        } else {
          response = await getUserPageApi(this.currentPage, this.pageSize)
          this.users = response.data.records
          this.total = response.data.total
        }
      } catch (err) {
        console.error('加载用户列表失败:', err)
      }
    },

    // 加载当前登录用户
    loadCurrentUser() {
      const userInfo = localStorage.getItem('userInfo')
      this.currentUser = userInfo ? JSON.parse(userInfo) : {}
    },

    // 刷新数据
    async refreshData() {
      try {
        await Promise.all([this.loadUserStats(), this.loadUsers()])
        alert('数据刷新成功')
      } catch (err) {
        alert('刷新失败: ' + (err.response?.data?.message || err.message))
      }
    },

    // 提升为管理员
    async promoteUser(userId) {
      if (confirm('确定设为管理员吗？')) {
        try {
          const user = this.users.find(u => u.id === userId)
          await updateUserApi({id: userId, role: 'ADMIN'})
          user.role = 'ADMIN'
          this.userStats.admins++
        } catch (err) {
          alert('操作失败: ' + (err.response?.data?.message || err.message))
        }
      }
    },

    // 取消管理员
    async demoteUser(userId) {
      if (confirm('确定取消管理员权限吗？')) {
        try {
          const user = this.users.find(u => u.id === userId)
          await updateUserApi({id: userId, role: 'USER'})
          user.role = 'USER'
          this.userStats.admins--
        } catch (err) {
          alert('操作失败: ' + (err.response?.data?.message || err.message))
        }
      }
    },

    // 删除用户
    async deleteUser(userId) {
      if (confirm('确定删除？此操作不可恢复！')) {
        try {
          await deleteUserApi(userId)
          this.users = this.users.filter(u => u.id !== userId)
          this.total--
          this.userStats.total--
          await this.refreshData()
        } catch (err) {
          alert('删除失败: ' + (err.response?.data?.message || err.message))
        }
      }
    },

    // 搜索防抖
    handleSearch() {
      clearTimeout(this.searchTimeout)
      this.searchTimeout = setTimeout(() => {
        this.currentPage = 1
        this.loadUsers()
      }, 300)
    },

    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.loadUsers()
      }
    },

    // 下一页
    nextPage() {
      if (this.currentPage * this.pageSize < this.total) {
        this.currentPage++
        this.loadUsers()
      }
    },

    // 日期格式化
    formatDate(dateString) {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }

    // 已删除：gotoReport 报表跳转方法
  }
}
</script>

<style scoped>
.admin-container {
  padding: 20px;
}
</style>